package priv.pront.code.algorithm_daily.acwing.search;

import java.util.*;
/**
 * @Description: https://www.acwing.com/problem/content/645/
 * @Author: pront
 * @Time:2024-06-19 15:33
 */
public class A643_动态网格 {

    static int T, R, C, N;
    static int[][] arr;
    static int[] dx = {0, -1, 0, 1}, dy = {-1, 0, 1, 0};
    static boolean[][] st;
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        T = sc.nextInt();
        int count = 0;
        while(T-- > 0){
            R = sc.nextInt();
            C = sc.nextInt();
            arr = new int[R][C];
            for(int i = 0; i < R; i++) {
                String[] s = sc.next().split("");
                for(int j = 0; j < C; j++) arr[i][j] = Integer.parseInt(s[j]);
            }
            count ++;
            N = sc.nextInt();
            System.out.println("Case #" + count + ":");
            while(N-- > 0){
                String act = sc.next();
                if(act.equals("Q")) System.out.println(query());
                else{
                    int x = sc.nextInt(), y = sc.nextInt(), z = sc.nextInt();
                    arr[x][y] = z;
                }
            }
        }
    }

    private static int query(){
        int ans = 0;
        st = new boolean[R][C];
        for(int i = 0; i < R; i++){
            for(int j = 0; j < C; j++){
                if(arr[i][j] == 1 && !st[i][j]){
                    ans ++;
                    dfs(i, j);
                }
            }
        }
        return ans;
    }

    private static void dfs(int x, int y){
        for(int i = 0; i < 4; i++){
            int nx = x + dx[i];
            int ny = y + dy[i];
            if(nx < 0 || nx >= R || ny < 0 || ny >= C || st[nx][ny] || arr[nx][ny] == 0) continue;
            st[nx][ny] = true;
            dfs(nx, ny);
        }
    }
}
